package com.brotherly.framework.storage;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;

import com.brotherly.util.ReusablePool;

public class SimpleStorage
{
    protected SharedPreferences preferences;
    protected SharedPreferences.Editor editor;
    protected ReusablePool<SimpleStorage> pools;

    public SimpleStorage()
    {}

    public void setSharedPreferences(SharedPreferences preferences, ReusablePool<SimpleStorage> pools)
    {
        this.preferences = preferences;
        this.pools = pools;
        begin();
    }

    public void clear()
    {
        if (editor != null)
            editor.clear();
    }

    public String get(String key)
    {
        return preferences.getString(key, null);
    }

    public void put(String key, String value)
    {
        if (editor != null)
            editor.putString(key, value);
    }

    @SuppressLint("CommitPrefEdits")
    public void begin()
    {
        editor = preferences.edit();
    }

    @SuppressLint("CommitPrefEdits")
    public void rollback()
    {
        editor = preferences.edit();
    }

    public void commit()
    {
        if (editor != null)
            editor.commit();
    }

    public void close()
    {
        pools.free(this);
    }

    public String getWithDefault(String key, String defaultValue)
    {
        return preferences.getString(key, defaultValue);
    }

    public void remove(String key)
    {
        // TODO Auto-generated method stub
        if (editor != null)
            editor.remove(key);
    }
}
